package t327.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

public class AlipayUtil {
    private static String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk7bimbRmUvrmL3eknqrF2DJYXIw6P37lMos11MuYauEDzeeUNdmD1k/mbvZCAVT7FCSWrU2VVDl7oL3TtPyIAH0uYFl6s5SGT4XmMH5fH1P3LOcuegK1VJ/7lWYRNzgX3eDO47PQBPV0lEDgUVGxjV0nDEp7UWKKzVkwKxptKcJ3TjspGeTQPb7lF7OI4eY6CPIEa8l3ujFRJvKFWapmxaRmVXMai3Ltfsg2xHvkCxvWlsZDvaBVDuOFfgx4/z+1HHyaAp45TQBE8smVKw8uHU13JXXz9LmA5hPJ4Rwi8nK3fTWsI/AHanZQfiSwBLoirEcyuE2FOaI8sfVLQTDjFwIDAQAB";
    private static String signType="RSA2";
/**
     * 生成订单号，格式为: yyyyMMddHHmmssSSS + 随机数3位
     * @return 订单号
     */
    public static String generateOutTradeNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timestamp = sdf.format(new Date());
        Random random = new Random();
        int num = random.nextInt(900) + 100;
        return timestamp + num;
    }
    private static AlipayClient alipayClient;

static{
    String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCB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BMwFlefobLomNPW9GxNrblFsg9zU78ARqAHThwCi1y0xf8YNXRVk3PGU1ghlhXMb6b/Q/aH8WwC0saa6TAlBy6YeJhP7hRUH8qvianCOgKcEapHc8I1k/BQ8HlEwi14Yt9jn/56oHXl5M1NdUiJRaJQJCX44+2seMn59tNfkOiPwKBgD/2xO4gEyblqnpeuCB+qOifzjbUfhwkbc8BVRCaX/QJ5kx5G5/GlOr1CF6D36kemvnLNzlPRhzDkQTkKFCI4CU6jSoH4VMpmQIP21+4VBA/62Lwzy2PEh8skqBBXliWqb5w91T0s0NOZMdYIOzthNiUTaAxmBLNSNo3WkpMxTUxAoGBAJ3/UqDgkFSc/nvbV/tD1gVTe/IHXWKaD9rB/A7qa9h0F50NPwHduQpkNCYzT+6bOCofct2NLVF1xM4bHT8dCNd6BXu7TzMy38GiBPCWPZriIdBxcr6dy782LEIKexsa8ryJO23C3UgnA7BjAwmuyK/lQz/eBlii9PdeODLxwb10";




    AlipayConfig alipayConfig = new AlipayConfig();


    alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");


    alipayConfig.setAppId("9021000122681498");


    alipayConfig.setPrivateKey(privateKey);


    alipayConfig.setFormat("json");


    alipayConfig.setAlipayPublicKey(alipayPublicKey);


    alipayConfig.setCharset("UTF8");


    alipayConfig.setSignType(signType);
    try {

        alipayClient = new DefaultAlipayClient(alipayConfig);

    } catch (AlipayApiException e) {
        System.out.println("支付宝客户端初始化异常，支付宝功能暂不能使用");
        e.printStackTrace();
    }

}

public static AlipayTradeRefundResponse refundForOrder(AlipayTradeRefundModel model){
    HashMap<String, String> map = new HashMap<>();
    AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
    request.setBizModel(model);
    AlipayTradeRefundResponse response = null;
    try {
        response = alipayClient.execute(request);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    return response;
}




public static AlipayTradePayResponse payForPayCode(AlipayTradePayModel model){

    AlipayTradePayRequest request = new AlipayTradePayRequest();
    request.setBizModel(model);
    AlipayTradePayResponse response = null;
    try {
        response = alipayClient.execute(request);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    return response;
}
public static AlipayTradePrecreateResponse preCreate(AlipayTradePrecreateModel model){

    AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
    request.setBizModel(model);
    request.setNotifyUrl("  http://by8n28.natappfree.cc/clothingManage_war_exploded/pay/confirmPay");
    AlipayTradePrecreateResponse response = null;
    try {
        response = alipayClient.execute(request);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }


    return response;
}

/* 将付款通知的请求变成map供后面验签使用*/
public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
    Map<String, String> retMap = new HashMap<String, String>();

    Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> entry : entrySet) {
        String name = entry.getKey();
        String[] values = entry.getValue();
        int valLen = values.length;

        if (valLen == 1) {
            retMap.put(name, values[0]);
        } else if (valLen > 1) {
            StringBuilder sb = new StringBuilder();
            for (String val : values) {
                sb.append(",").append(val);
            }
            retMap.put(name, sb.toString().substring(1));
        } else {
            retMap.put(name, "");
        }
    }

    return retMap;
}
public static Boolean verify(Map<String, String> parameterMap){
    try {
        return AlipaySignature.verifyV1(parameterMap,alipayPublicKey,parameterMap.get("charset"), signType);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    return false;
}



}